#include "request.pb.h"
#include "muduo/proto/codec.h"
#include "muduo/proto/dispatcher.h"

#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpServer.h"
#include <iostream>
#include <unordered_map>

class Server
{
public:
    // 四个操作序列化与反序列化结构体的四个智能指针
    typedef std::shared_ptr<bit::TranslateRequest> TranslateRequestPtr;
    typedef std::shared_ptr<bit::AddRequest> AddRequestPtr;

    Server(int port)
        : _server(&_baseloop, muduo::net::InetAddress("0.0.0.0", port),
                  "Server", muduo::net::TcpServer::kReusePort),
          _dispatcher(std::bind(&Server::onUnknownMessage, this, std::placeholders::_1,
                                std::placeholders::_2, std::placeholders::_3)),
          _codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher, std::placeholders::_1,
                           std::placeholders::_2, std::placeholders::_3))
    {
        // 将处理翻译的函数OnTranslate和处理加法的函数OnAdd注册到dispatcher中去
        _dispatcher.registerMessageCallback<bit::TranslateRequest>(std::bind(&Server::onTranslate, this,
                                                                             std::placeholders::_1,
                                                                             std::placeholders::_2,
                                                                             std::placeholders::_3));
        _dispatcher.registerMessageCallback<bit::AddRequest>(std::bind(&Server::onAdd, this,
                                                                       std::placeholders::_1,
                                                                       std::placeholders::_2,
                                                                       std::placeholders::_3));
        _server.setConnectionCallback(std::bind(&Server::onConnection, this, std::placeholders::_1));

        _server.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &_codec, std::placeholders::_1,
                                             std::placeholders::_2, std::placeholders::_3));
    }
    void start() // 启动服务器
    {
        _server.start(); // 开始监听连接
        _baseloop.loop();
    }

private:
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected())
            LOG_INFO << "新连接到来了\n";
        else
            LOG_INFO << "连接断开了\n";
    }

    void onUnknownMessage(const muduo::net::TcpConnectionPtr &conn,
                          const MessagePtr &message,
                          muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
        conn->shutdown();
    }

    std::string translate(const std::string str)
    {
        std::unordered_map<std::string, std::string> dict = {{"你好", "hello"},
                                                             {"翻译", "translate"},
                                                             {"hello", "你好"},
                                                             {"吃的啥", "内江牛肉面"}};
        auto iter = dict.find(str);
        if (iter == dict.end())
            return "没听懂";
        return dict[str];
    }

    void onTranslate(const muduo::net::TcpConnectionPtr &conn, const TranslateRequestPtr &message, muduo::Timestamp)
    {
        // 1.提取有效消息，需要翻译的内容
        std::string req_msg = message->msg();
        // 2.得到翻译的结果
        std::string resp_msg = translate(req_msg);
        // 3.组织响应
        bit::TranslateResponse resp;
        resp.set_msg(resp_msg);
        // 4.发送响应
        _codec.send(conn, resp);
    }

    void onAdd(const muduo::net::TcpConnectionPtr &conn, const AddRequestPtr &message, muduo::Timestamp)
    {
        int num1 = message->num1();
        int num2 = message->num2();
        int result = num1 + num2;
        // 1.组织响应
        bit::AddResponse resp;
        resp.set_result(result);
        // 2.发送响应
        _codec.send(conn, resp);
    }

private:
    muduo::net::EventLoop _baseloop; // epoll
    muduo::net::TcpServer _server;   // 服务器的整体实现逻辑
    ProtobufDispatcher _dispatcher;  // 消息分发器
    ProtobufCodec _codec;            // 实现消息的编解码
};

int main()
{
    Server server(8080);
    server.start();
    return 0;
}